package com.web.servlet.chapter;

import com.web.bean.chapter.Chapter;
import com.web.bean.novel.Novel;
import com.web.dao.chapter.ChapterDaoImpl;
import com.web.dao.novel.NovelDaoImpl;
import com.web.result.Result;
import com.web.service.chapter.ChapterServiceImpl;
import com.web.utils.DBUtil;
import com.web.utils.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @autor Chen
 * @create 2021--25-14:20
 * @desc
 */
@WebServlet("/chapter/*")
public class ChapterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI().replaceAll("/chapter/", "");
        if ("addChapter".equals(uri)) addChapter(req, resp);
        if ("updateChapter".equals(uri)) updateChapter(req, resp);
        if ("deleteChapterById".equals(uri)) deleteChapterById(req, resp);
        if ("selectChapters".equals(uri)) selectChapters(req, resp);
        if ("selectChapterById".equals(uri)) selectChapterById(req, resp);
        if ("read".equals(uri)) read(req, resp);
        if ("next".equals(uri)) next(req,resp);
        if ("last".equals(uri)) last(req,resp);
        if ("toParagraph".equals(uri)) toParagraph(req,resp);
        if ("toUploadParagraph".equals(uri)) toUploadParagraph(req,resp);
    }

    private void toUploadParagraph(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String nid = req.getParameter("nid");
        HttpSession session = req.getSession();
        session.setAttribute("nid",nid);
        req.getRequestDispatcher("/uploadParagraph.jsp").forward(req,resp);
    }

    private void toParagraph(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String nid = req.getParameter("nid");
        HttpSession session = req.getSession();
        session.setAttribute("nid",nid);
        req.getRequestDispatcher("/paragraph.jsp").forward(req,resp);
    }

    private void last(HttpServletRequest req, HttpServletResponse resp) {
        String chapterID = req.getParameter("chapterID");
        DBUtil dbUtil = DBUtil.getInstance();
        HttpSession session = req.getSession();
        try {
            ChapterDaoImpl chapterDao = new ChapterDaoImpl(dbUtil.getConnection());
            Chapter chapter = chapterDao.selectChapterById(chapterID);
            String nid = chapter.getNid();
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            List<Chapter> chapters = chapterService.selectChapters(nid);
            for (int i = 0; i < chapters.size(); i++) {
                if (chapterID.equals(chapters.get(i).getChapterid())){
                    if (i-1>=0){
                        session.setAttribute("chapterID",chapters.get(i-1).getChapterid());
                        req.setAttribute("cname",chapters.get(i-1).getCname());
                    }
                    break;
                }
            }
            req.getRequestDispatcher("/novelRead.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
    }

    private void next(HttpServletRequest req, HttpServletResponse resp) {
        String chapterID = req.getParameter("chapterID");
        DBUtil dbUtil = DBUtil.getInstance();
        HttpSession session = req.getSession();
        try {
            ChapterDaoImpl chapterDao = new ChapterDaoImpl(dbUtil.getConnection());
            Chapter chapter = chapterDao.selectChapterById(chapterID);
            String nid = chapter.getNid();
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            List<Chapter> chapters = chapterService.selectChapters(nid);
            for (int i = 0; i < chapters.size(); i++) {
                if (chapterID.equals(chapters.get(i).getChapterid())){
                    if (i+1<chapters.size()){
                        session.setAttribute("chapterID",chapters.get(i+1).getChapterid());
                        req.setAttribute("cname",chapters.get(i+1).getCname());
                    }
                    break;
                }
            }
            req.getRequestDispatcher("/novelRead.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
    }

    private void read(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String chapterID = req.getParameter("chapterID");
        HttpSession session = req.getSession();
        session.setAttribute("chapterID", chapterID);
        DBUtil dbUtil = DBUtil.getInstance();
        try {
            ChapterDaoImpl chapterDao = new ChapterDaoImpl(dbUtil.getConnection());
            Chapter chapter = chapterDao.selectChapterById(chapterID);
            String cname = chapter.getCname();
            req.setAttribute("cname",cname);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
        req.getRequestDispatcher("/novelRead.jsp").forward(req, resp);
    }

    private void selectChapters(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String nid = req.getParameter("nid");
        Result result = new Result();
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        try {
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            List<Chapter> chapters = chapterService.selectChapters(nid);
            result.setFlag(true);
            result.setMessage("查询成功");
            result.setData(chapters);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage(e.getMessage());
        } finally {
            JSONWriter.writeJSON(result,resp);
        }

    }


    private void selectChapterById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String chapterID = req.getParameter("chapterID");
        HttpSession session = req.getSession();
        session.setAttribute("chapterID", chapterID);
        Result result = new Result();
        DBUtil dbUtil = DBUtil.getInstance();
        try {
            ChapterDaoImpl chapterDao = new ChapterDaoImpl(dbUtil.getConnection());
            Chapter chapter = chapterDao.selectChapterById(chapterID);
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            List<String> content = chapterService.selectChapterById(chapterID);
            result.setFlag(true);
            result.setMessage("读取成功");
            result.setData(content);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage(e.getMessage());
        } finally {
            dbUtil.close();
            JSONWriter.writeJSON(result, resp);
//            req.getRequestDispatcher("/novelRead.jsp").forward(req, resp);
        }
    }

    private void deleteChapterById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String chapterID = req.getParameter("chapterID");
        Result result = new Result();
        try {
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            chapterService.deleteChapter(chapterID);
            result.setFlag(true);
            result.setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage(e.getMessage());
        } finally {
            req.getRequestDispatcher("/uploadParagraph.jsp").forward(req, resp);
        }
    }

    private void updateChapter(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String chapterID = req.getParameter("chapterID");
        String chapterNum = req.getParameter("chapterNum");
        String name = req.getParameter("name");
        String cname = "第" + chapterNum + "章" + " " + name;
        String content = req.getParameter("content");
        FileWriter writer = null;
        DBUtil dbUtil = DBUtil.getInstance();
        Result result = new Result();
        try {
            ChapterDaoImpl chapterDao = new ChapterDaoImpl(dbUtil.getConnection());
            Chapter chapter = chapterDao.selectChapterById(chapterID);
            String csrc = chapter.getCsrc();
            File file = new File(csrc);
            if (file.exists()) {
                file.delete();
            } else {
                throw new Exception("文件不存在");
            }
            NovelDaoImpl novelDao = new NovelDaoImpl(dbUtil.getConnection());
            Novel novel = novelDao.selectById(chapter.getNid());
            csrc = novel.getNsrc() + "\\" + cname;
            writer = new FileWriter(csrc);
            writer.write(content);
            writer.flush();
            chapter.setCsrc(csrc);
            chapter.setCname(cname);
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            chapterService.updateChapter(chapter);
            result.setFlag(true);
            result.setMessage("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage(e.getMessage());
        } finally {
            dbUtil.close();
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            req.getRequestDispatcher("uploadParagraph.jsp").forward(req, resp);
        }


    }

    private void addChapter(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String chapterNum = req.getParameter("chapterNum");
        String name = req.getParameter("name");
        String cname = "第" + chapterNum + "章" + " " + name;
        String nid = req.getParameter("nid");
        String content = req.getParameter("content");
        FileWriter writer = null;
        String chapterid = UUID.randomUUID().toString().replaceAll("-", "");
        Result result = new Result();
        DBUtil dbUtil = DBUtil.getInstance();
        try {
            NovelDaoImpl novelDao = new NovelDaoImpl(dbUtil.getConnection());
            Novel novel = novelDao.selectById(nid);
            String csrc = novel.getNsrc() + "\\" + cname;
            writer = new FileWriter(csrc);
            writer.write(content);
            writer.flush();
            Chapter chapter = new Chapter();
            chapter.setNid(nid);
            chapter.setChapterid(chapterid);
            chapter.setCname(cname);
            chapter.setCsrc(csrc);
            ChapterServiceImpl chapterService = new ChapterServiceImpl();
            chapterService.addChapter(chapter);
            result.setFlag(true);
            result.setMessage("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage(e.getMessage());
        } finally {
            dbUtil.close();
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            req.getRequestDispatcher("uploadParagraph.jsp").forward(req, resp);
        }
    }
}
